package com.everbest.framework.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.everbest.system.domain.SysUser;
import com.everbest.system.service.ISysUserService;

public class PhoneAndVerificationCodeShiroRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        PhoneAndVerificationCodeToken phoneToken = (PhoneAndVerificationCodeToken)token;
        String phone = (String)phoneToken.getPrincipal();
        SysUser user = userService.selectUserByPhoneNumber(phone);
        // 因为没有密码，并且验证码在之前就验证了 所以我这里没有验证密码
        if (user == null) {
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(user, phone, getName());
    }

    /**
     * 用来判断是否使用当前的 realm
     * 
     * @param var1
     *            传入的token
     * @return true就使用，false就不使用
     */
    @Override
    public boolean supports(AuthenticationToken var1) {
        return var1 instanceof PhoneAndVerificationCodeToken;
    }

}
